//
//  ZLExamBeiginSheetViewController.m
//  ZLExamination
//
//  Created by Zheng on 2017/8/21.
//  Copyright © 2017年 Zheng. All rights reserved.
//

#import "ZLExamBeiginSheetViewController.h"

#import "ZLExamBeginSheetCell.h"
#import "ZLExamBeginModel.h"
#import "ZLExamBeginSheetCommitView.h"
#import "ZLExamResultViewController.h"

@interface ZLExamBeiginSheetViewController ()

@property (nonatomic, strong) UIButton *commitPaperBtn; // 交卷
@property (nonatomic, strong) ZLExamBeginSheetCommitView *commitView; //交卷提示
@property (nonatomic, strong) UILabel *timeLbl; //计时

@property (nonatomic) BOOL singleAllAnswer; //单选全部回答
@property (nonatomic) BOOL multipleAllAnswer; //多选全部回答
/** 所有题的考试答案数组*/
@property (nonatomic,strong) NSMutableArray* allAnswerArray;
@end

@implementation ZLExamBeiginSheetViewController

#pragma mark - 点击事件
- (void)commitPaperClick:(UIButton *)sender {
#pragma mark 是否交卷弹窗提示
    
    _singleAllAnswer = YES;
    _multipleAllAnswer = YES;
    
    [_questions[0] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ZLExamBeginListModel *model = (ZLExamBeginListModel *)obj;
        if(model.isAnswer == NO) {
            _singleAllAnswer = NO;
            *stop = YES;
        }
    }];
    
    [_questions[1] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ZLExamBeginListModel *model = (ZLExamBeginListModel *)obj;
        if (model.isAnswer == NO) {
            _multipleAllAnswer = NO;
            *stop = YES;
        }
    }];
    
    if (_singleAllAnswer&&_multipleAllAnswer) {
        [_commitView showCommitViewAllAnswer];
    } else {
        kCX_LOG(@"你有题目没有答完");
        [_commitView showCommitViewUnAnswer];
//        [_commitView showCommitViewAutoCommit];
    }
}

#pragma mark 确定交卷
- (void)clickActionCallBack {
    _allAnswerArray = [NSMutableArray array];
    __weak typeof(self) weakSelf = self;
    [_commitView setEnterCallBack:^{
        kCX_LOG(@"交卷");
        NSMutableArray<ZLExamBeginListModel *> *singleArr = weakSelf.questions[0];
        NSMutableArray<ZLExamBeginListModel *> *multipleArr = weakSelf.questions[1];
        //打印单选选择的内容
        [singleArr enumerateObjectsUsingBlock:^(ZLExamBeginListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.questionAnswer) {
                 NSString *answerStr = [NSString stringWithFormat:@"%@:%@", obj.n_id, obj.questionAnswer];
                NSLog(@"%@", answerStr);
                [weakSelf.allAnswerArray addObject:answerStr];

            } else {
                NSString *answerStr = [NSString stringWithFormat:@"%@: ", obj.n_id];
                NSLog(@"%@", answerStr);
                [weakSelf.allAnswerArray addObject:answerStr];
            }
        }];
        
        //打印多选选择的内容
        [multipleArr enumerateObjectsUsingBlock:^(ZLExamBeginListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.answers.count != 0) {
                //obj.answers数组里面按照abcd 排序 后放到resultArray数组里
                NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch|NSNumericSearch|
                NSWidthInsensitiveSearch|NSForcedOrderingSearch;
                
                NSComparator sort = ^(NSString *obj1,NSString *obj2){
                    
                    NSRange range = NSMakeRange(0,obj1.length);
                    
                    return [obj1 compare:obj2 options:comparisonOptions range:range];
                };
                NSArray *resultArray = [obj.answers sortedArrayUsingComparator:sort];
                //                obj.answers
                NSString *tempStr = [resultArray componentsJoinedByString:@""];
                NSString *answerStr = [NSString stringWithFormat:@"%@:%@", obj.n_id, tempStr];
                NSLog(@"%@", answerStr);
                [weakSelf.allAnswerArray addObject:answerStr];
                
            } else {
                NSString *answerStr = [NSString stringWithFormat:@"%@: ", obj.n_id];
                NSLog(@"%@", answerStr);
                [weakSelf.allAnswerArray addObject:answerStr];
            }
        }];
        NSString *scoreStr = [weakSelf.allAnswerArray componentsJoinedByString:@"|"];
        NSLog(@"%@", scoreStr);
        //提交考试信息
        [weakSelf submitExamLoadDataWith:scoreStr];
    }];
}

//提交考试数据
- (void)submitExamLoadDataWith:(NSString *)scoreStr
{
    NSDictionary *param = @{@"user_paper_id":_examModel.user_paper_id,
                            @"score" : scoreStr
                            };
    NSLog(@"%@", param);
    YCRequestDataService *manager = [YCRequestDataService sharedManager];
    [manager Post:@"paper/paper/sub_paper" parameters:param success:^(id response) {
        if (response[@"error_code"]) {
            NSLog(@"%@",response[@"error_msg"]);
            [manager showHUDSleepText:self withTitle:response[@"error_msg"]];
        } else {
            
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"user_paper_id"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            ZLExamResultViewController *examResultVC = [[ZLExamResultViewController alloc] init];
            examResultVC.user_paper_id = [_examModel.user_paper_id stringValue];
            examResultVC.curriculum_id = _curriculum_id;
            [self.navigationController pushViewController:examResultVC animated:YES];
        }
        
    } failure:^{
        NSLog(@"网络或服务器出错");
    }];
}
//点击返回按钮
- (void)scroolToDesignationRowWith:(NSInteger)rowNumber {
    if (_clickCallBack) {
        _clickCallBack(rowNumber);
//        [self dismissViewControllerAnimated:YES completion:^{
//            
//        }];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 传值
- (void)setQuestions:(NSArray<NSMutableArray *> *)questions {
    _questions = questions;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self showBackButtonWithTitle:@"╳" withFont:[UIFont boldSystemFontOfSize:20]];
    
    self.navigationItem.title = @"答题卡";
    
    [self.myTableView registerClass:[ZLExamBeginSheetCell class] forCellReuseIdentifier:kZLExamBeginSheetCell_ID];
    self.myTableView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.commitPaperBtn];
    
    [self.view addSubview:self.commitView];
    [self.view bringSubviewToFront:self.commitView];
    
//    [[UIApplication sharedApplication].delegate.window addSubview:self.commitView];
    
    [self clickActionCallBack];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [_commitPaperBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    
    [self.myTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(_commitPaperBtn.mas_top);
    }];
}


#pragma mark - 子视图
- (ZLExamBeginSheetCommitView *)commitView {
    if (!_commitView) {
        _commitView = [[ZLExamBeginSheetCommitView alloc] initWithFrame:(CGRect){0, 0, kSCREEN_WIDTH, kSCREENH_HEIGHT}];
    }
    return _commitView;
}

- (UIButton *)commitPaperBtn {
    if (!_commitPaperBtn) {
        _commitPaperBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _commitPaperBtn.backgroundColor = kMY_BLUE_COLOR;
        [_commitPaperBtn setTitle:@"交卷" forState:UIControlStateNormal];
        [_commitPaperBtn addTarget:self action:@selector(commitPaperClick:) forControlEvents:UIControlEventTouchUpInside];
        _commitPaperBtn.titleLabel.font = kMyFont(15);
    }
    return _commitPaperBtn;
}


#pragma mark - tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    
    ZLExamBeginSheetCell *cell = [tableView dequeueReusableCellWithIdentifier:kZLExamBeginSheetCell_ID forIndexPath:indexPath];
    
    if (indexPath.section == 0) {
        [cell setNumbersWithRows:[_questions[0] count] withSingles:_questions[indexPath.section]];
        
    } else {
        [cell setNumbersWithRows:[_questions[1] count] withMultiple:_questions[indexPath.section] withSingleRows:[_questions[0] count]];
    }
    
    cell.clickCallBack = ^(NSInteger number) {
        [weakSelf scroolToDesignationRowWith:number];
    };
    
    return cell;
}


#pragma mark - tableview delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger rows = 0;
    
    if (indexPath.section == 0) {
        CGFloat a = [_questions[0] count]/5.;
        NSInteger b = [_questions[0] count]/5;
        rows = a>b? b+1: b;
    } else {
        CGFloat a = [_questions[1] count]/5.;
        NSInteger b = [_questions[1] count]/5;
        rows = a>b? b+1: b;
    }
    
    return rows*(kSCREEN_WIDTH/5);
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return @"单选题";
    } else {
        return @"多选题";
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

#pragma mark - 返回
//- (void)backBarButtonPressed:(id)sender {
//    [self dismissViewControllerAnimated:YES completion:^{}];
//}

#pragma mark - 内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
